package cn.aylog.accountdemo.configs.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class CommonUtils {

    private CommonUtils() {}

    /**
     * 构建返回参数
     * @param data 返回的数据
     * @param message 信息
     * @param success 操作是否成功
     * @return 返回json字符串
     */
    public static String createResponse(Object data, String message, Boolean success) {
        Map<String, Object> map = new HashMap<>();
        map.put("data", data);
        map.put("message", message);
        map.put("success", success);
        String jsonStr = null;
        try {
            jsonStr = new ObjectMapper().writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // 记录并返回错误信息
            map.put("data", null);
            map.put("message", e.getMessage());
            map.put("success", false);
            try {
                jsonStr = new ObjectMapper().writeValueAsString(map);
            } catch (JsonProcessingException ex) {
                ex.printStackTrace();
            }
        }
        return jsonStr;
    }
}
